package com.baox.agridata.synchronous.schedule;


import com.alibaba.fastjson.JSON;
import com.baox.agridata.synchronous.constant.TaskNameConstant;
import com.baox.agridata.synchronous.entity.quanguo.ZsAbp;
import com.baox.agridata.synchronous.entity.quanguo.ZsApply;
import com.baox.agridata.synchronous.entity.quanguo.ZsReturns;
import com.baox.agridata.synchronous.entity.shanxi.SxAgricultureTask;
import com.baox.agridata.synchronous.entity.shanxi.TIMMUNEEarTagRecord;
import com.baox.agridata.synchronous.service.quanguo.ZsAbpService;
import com.baox.agridata.synchronous.service.quanguo.ZsApplyService;
import com.baox.agridata.synchronous.service.shanxi.*;
import com.baox.agridata.synchronous.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;

@Slf4j
@Component
@Configuration
public class LocalPushDataToAgriculturalEarTag {

    @Autowired
    private SxAgricultureTaskService sxAgricultureTaskService;

    @Autowired
    private TBaseRegionService tBaseRegionService;

    @Autowired
    private ZsApplyService zsApplyService;

    @Autowired
    private ZsAbpService zsAbpService;


    @Autowired
    private TZsApplyService tZsApplyService;

    @Autowired
    private TZsAbpService tZsAbpService;

    @Autowired
    private TZsReturnsService tZsReturnsService;

    @Autowired
    private UsersService usersService;


    @Value("${DbConfig.ZSABPStartTime}")
    private String ZSABPStartTime;

    @Value("${DbConfig.ZSRETURNSStartTime}")
    private String ZSRETURNSStartTime;   //耳标回传数据

    @Autowired
    private SplitDataSummary splitDataSummary;

    @Scheduled(cron = "0 45 23 * * ?")
    public void getZsApplyData() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.getZsApplyData);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("【农业部zs_apply】定时任务开始同步");
            try {
                List<ZsApply> zsApplies = zsApplyService.selectZsApplyList();
                if (zsApplies != null && zsApplies.size() > 0) {
                    List<ZsApply> addList = new ArrayList<>();  //新增的集合
                    List<ZsApply> updateList = new ArrayList<>();  //新增的集合
                    Integer addCount = 0, updateCount = 0;
                    for (ZsApply zsApply : zsApplies) {
                        String id = tZsApplyService.selectZsApplyById(zsApply.getId());  //如果数据不存在，则加入inser的集合中
                        if (StringUtils.isEmpty(id)) {
                            addList.add(zsApply);
                        } else {
                            updateList.add(zsApply);
                        }
                    }
                    if (addList.size() > 0) addCount = tZsApplyService.batchZsApply(addList);
                    if (updateList.size() > 0) updateCount = tZsApplyService.batchUpdateZsApply(updateList);
                    if (zsApplies != null && zsApplies.size() > 0) {
                        if (addCount.intValue() > 0 || updateCount.intValue() > 0) {
                            //delete data
                            Integer deleteCount = zsApplyService.deleteZsApplyList(zsApplies);
                            log.info("zs_apply删除的数量为{}", deleteCount.intValue());
                        }
                    }
                    log.info("【农业部zs_apply】定时数据获取,insert条目为：{},update条目数为：{}", addCount.intValue(), updateCount.intValue());
                } else {
                    log.info("【农业部zs_apply】本次未查询到数据");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("【农业部zs_apply】任务未开启");
        }
    }


    @Scheduled(cron = "0 55 23 * * ?")
    public void getZsAbpDataDownLoad() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.getZsAbpData);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("【农业部zs_abp】开始获取");
            try {
                List<ZsApply> zsApplies = tZsApplyService.selectZsApplyAllData(); //查询所有的任务id，去找耳标标识号数据
                List<ZsAbp> zsAbps = zsAbpService.selectZsAbpListData(zsApplies);
                log.info("abp本次select的条目数为：{}", zsAbps.size());
                if (zsAbps != null && zsAbps.size() > 0) {
                    List<ZsAbp> addList = new ArrayList<>();
                    for (ZsAbp abp : zsAbps) {
                        Integer dataIsExist = tZsAbpService.selectTZsAbpById(abp.getId());
                        if (dataIsExist == null || dataIsExist.intValue() == 0) addList.add(abp);
                    }
                    Integer insertCount, deleteCount;
                    if (addList != null && addList.size() > 0) {  //如果有新增数据
                        insertCount = splitDataSummary.interceptListTZSABPList(addList);
                        log.info("abp本次insert到本地的条目数为：{}", insertCount.intValue());
                        //执行删除
                        deleteCount = splitDataSummary.interceptListTZSABPListDelete(zsAbps);
                        log.info("abp本次insert条目数为：{}，delete条目数为：{}", insertCount.intValue(), deleteCount.intValue());
                    } else {
                        //执行删除
                        deleteCount = splitDataSummary.interceptListTZSABPListDelete(zsAbps);
                        log.info("abp本次没有查询到数据，全部删除，delete到本地的条目数为：{}", deleteCount.intValue());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("【农业部zs_abp】任务未开启");
        }
    }


    /**
     * 组装本地耳标数据
     */
    @Scheduled(cron = "0 59 23 * * ?")
    public void assembleTIMMUNEEarTagRecordData() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.getZsAbpData);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("【组装本地耳标数据】开始获取");
            try {
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "ZSABP";
                String l_fileName = "StartTimeConfig.txt";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, l_fileName)) {
                    ZSABPStartTime = l_file.readLastLineV2(l_filePath, l_fileName);
                }
                List<ZsAbp> zsAbps = tZsAbpService.selectTZsAbpListData(ZSABPStartTime);
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                log.info("zsAbps  size : {} ", zsAbps.size());
                if (zsAbps != null && zsAbps.size() > 0) {
                    List<TIMMUNEEarTagRecord> insertList = new ArrayList<>();
                    Integer addCount = 0;
                    for (ZsAbp zsAbp : zsAbps) {
                        TIMMUNEEarTagRecord timmuneEarTagRecord = new TIMMUNEEarTagRecord();
                        timmuneEarTagRecord.setSourceId(zsAbp.getApplyId() + ":" + "农业部数据做标识");  //sourceId
                        timmuneEarTagRecord.setTransType(1013);           //transType
                        Map animalTypeMap = DicDataTurnUtil.animalTypeTurnMap(zsAbp.getDwdm());
                        if (animalTypeMap != null && !animalTypeMap.isEmpty()) {
                            Integer animalId = MapUtil.getInteger(animalTypeMap, "id");
                            timmuneEarTagRecord.setAnimalId(animalId);     //animalId
                        }
                        String beginCode = zsAbp.getBeginCode().toString();
                        String endCode = zsAbp.getEndCode().toString();
                        String prefix = beginCode.substring(0, 7);
                        String rangeStart = beginCode.substring(7);
                        String rangeEnd = endCode.substring(7);
                        timmuneEarTagRecord.setPrefix(prefix);          //prefix
                        timmuneEarTagRecord.setRangeStart(rangeStart);  //rangeStart
                        timmuneEarTagRecord.setRangeEnd(rangeEnd);      //rangeEnd
                        timmuneEarTagRecord.setTotalNumber(zsAbp.getEarmarkAmount());   //totalNumber
                        timmuneEarTagRecord.setIsSignFor(1016);                         //isSignFor
                        String inRegionQhdm = zsAbp.getQhdm() + "000000";
                        String RegionFullName = null;
                        Map inRegionJson = tBaseRegionService.selectRegionInfoByRegionCode(inRegionQhdm);
                        if (inRegionJson != null && !inRegionJson.isEmpty()) {
                            Integer inRegionId = MapUtil.getInteger(inRegionJson, "ID");
                            RegionFullName = MapUtil.getString(inRegionJson, "RegionFullName");
                            String region = JSON.toJSONString(inRegionJson);
                            timmuneEarTagRecord.setInRegionId(inRegionId);                  //inRegionId
                            timmuneEarTagRecord.setRegion(region);                          //region
                        }
                        String inUserMid = usersService.selectInUserMid(zsAbp.getReceiveOrg(), inRegionQhdm);
                        Map<String, Object> inUserMap = new HashMap<>();
                        inUserMap.put("key", inUserMid);
                        inUserMap.put("Name", zsAbp.getReceiveOrg());
                        String inUserJson = JSON.toJSONString(inUserMap);
                        String signInRegionPerson = RegionFullName + "-" + zsAbp.getReceiveOrg();
                        timmuneEarTagRecord.setSignInRegionPerson(signInRegionPerson);              //signInRegionPerson
                        timmuneEarTagRecord.setInUserJson(inUserJson);                              //inUserJson
                        timmuneEarTagRecord.setInUser(inUserMid);                                   //inUser
                        timmuneEarTagRecord.setApplyId(zsAbp.getApplyId());                         //applyId
                        timmuneEarTagRecord.setBoxCode(zsAbp.getBoxCode());                         //boxCode
//                      timmuneEarTagRecord.setPackageNumber(zsAbp.getPackageNumber());             //packageNumber
                        timmuneEarTagRecord.setMid(StringStrategy.getUUIDNonHyphen());  //mid
                        insertList.add(timmuneEarTagRecord);
                    }
                    if (insertList.size() > 0)
                        addCount = splitDataSummary.interceptListTIMMUNEEarTagRecord(insertList);
                    log.info("【组装本地耳标数据】定时数据获取,本期开始时间节点为:{},下期开始时间节点为:{},insert条目为：{}", ZSABPStartTime, endTime, addCount.intValue());
                } else {
                    log.info("【组装本地耳标数据】本次未查询到数据,本期时间节点为:{}-----{}", ZSABPStartTime, endTime);
                }
                l_file.WriteContent(endTime, l_filePath, l_fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("【组装本地耳标数据】任务未开启");
        }
    }


    /**
     * 追溯-任务/箱/包/耳标表 (每日23点30分执行)
     */
    @Scheduled(cron = "0 30 23 * * ?")
    public void sendZsReturnsData() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.sendReturnData);
        if (sxAgricultureTask != null && sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【农业部zs_return】定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "ZsReturns";
                String l_fileName = "StartTimeConfig.txt";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, l_fileName)) {
                    ZSRETURNSStartTime = l_file.readLastLineV2(l_filePath, l_fileName);
                }
                // 写入当前时间
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                List<ZsReturns> l_list = tZsReturnsService.selectTZsReturnsData(ZSRETURNSStartTime, endTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer result = splitDataSummary.interceptListZsReturn(l_list);
                    log.info("【农业部zs_return】，本期时间节点为:{},下次时间节点为:{},同步数据总条目为：{},数据库插入结果为：{}", ZSRETURNSStartTime, endTime, l_list.size(), result.intValue());
                } else {
                    log.info("【农业部zs_return】,本期时间节点为:{},同步数据总条目为：{},", ZSRETURNSStartTime, l_list.size());
                }
                l_file.WriteContent(endTime, l_filePath, l_fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("开始【农业部zs_return】同步任务未开启");
        }
    }


}
